const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('koa2-cors');
const koajwt = require('koa-jwt');

const index = require('./routes/index');
const user = require('./routes/user');

const dbconn = require('./middle/dbconn');
const sysconfig = require('./utils/sysconfig');

// error handler
onerror(app);
app.use(cors());

//全局接口生成一个sqlconn
//并在接口最后关闭sqlconn
app.use(
  dbconn().unless({
    path: []
  })
);

// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text'],
  })
);
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(
  views(__dirname + '/views', {
    extension: 'pug',
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  ctx.state.config = sysconfig;
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// token处理
// koajwt会自动解析token并放入ctx.state.user
const tokenKey = 'luckhall';
app.use(
  koajwt({
    secret: tokenKey
  }).unless({
    path: ['/user/login']
  })
);

// routes
app.use(index.routes(), index.allowedMethods());
app.use(user.routes(), user.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
